import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";

import ByCell from "../ui/ByCell";
import FormInput from "../common/FormInput";
import PopupContainer from "./PopupContainer";

import ByButton from "@/components/ui/ByButton";
import useForm from "@/hooks/useForm";
import ApiWorkflow from "@/api/workflow";

type PopupRejectedEvent = {
  onCancel: () => void;
};

export default ({
  state,
  workItemId,

  onCancel,
  onSuccess
}: PopupRejectedEvent & {
  state: 1 | 2,
  workItemId: number,
  onSuccess: () => void;
}) => {

  const isPassed = state === 1
  const title = isPassed ? '通过' : "驳回"


  // 审批操作
  const { loading, model, setModel, submit } = useForm(ApiWorkflow.approveAudit, {
    showLoading: true,
    defaultModel: {
      workItemId,
      auditRemark: "",
      auditResult: state,
    },
    onSuccess() {
      Taro.showToast({ title: "操作成功" });
      onSuccess()
    },
  });

  /**
   * @param auditResult 审核结果 1通过，2驳回
   * @param auditRemark 审核原因/备注
   */
  const handleSubmit = async () => {
    const { confirm } = await Taro.showModal({
      title: `审批${title}`,
      content: "确定进行本次审批操作？",
    });

    confirm && submit()
  };

  const disabled = !isPassed && !model.auditRemark.trim()
  return (
    <PopupContainer safeFooter title={`审批${title}`} onCancel={onCancel}>
      <View className="px-4">
        <View className="font-bold py-3 border-b-1 border-line-light">
          您确定{title}本次申请？
        </View>

        <View className="mt-2">
          <ByCell label={isPassed ? "审批备注" : "驳回原因"} requierd={!isPassed} vertical>
            <FormInput
              type="textarea"
              placeholder="请输入"
              value={model.auditRemark}
              onChange={e => setModel({ auditRemark: e })}
            />
          </ByCell>
        </View>

        <ByButton
          size="large"
          loading={loading}
          disabled={disabled}
          className="w-2/3 mt-6 mb-3"
          onClick={handleSubmit}
        >
          提交
        </ByButton>
      </View>
    </PopupContainer>
  );
};
